<?php

/**
 * 获取tpl信息
 */
function getTplData(){
    $mobile_enable=extendSetting("mobile_enable");
    $webSetting=siteSetting("sitePcTemplateDir");
    $defaultTemplate=config("template.default_pc","");
    $tpl = $webSetting?$webSetting:$defaultTemplate;

    if($mobile_enable=="1"){
        if(is_mob()){
            $webSetting=siteSetting("siteMobileTemplate");
            $defaultTemplate=config("template.default_mobile","");
            $tpl = $webSetting?$webSetting:$defaultTemplate;
        }
    }

    $data=array();
    $data["tpl"]=$tpl;
    $data["defaultTemplate"]=$defaultTemplate;
    return $data;
}

/**
 * 加载模板
 * @param string $template
 * @param string $data
 * @return string
 */
function template($template = 'index',$templatePath=null) {
    $tplData=getTplData();
    $tplRefresh = config("template.template_refresh",0);

    //检测$templatePath 是否是插件，如果是插件则获取插件对应的配置文件，然后更新tpl变量
    $templatePath = $templatePath?$templatePath.'/':"";
    if(($pos=stripos($template,"."))===false){
        $to = YIFANG_CACHE.'/tpl/'.$templatePath.$tplData["tpl"].'/'.$template.'.php';
        $extend='.html';
    }else{
        $extend="";
        $to = YIFANG_CACHE.'/tpl/'.$templatePath.$tplData["tpl"].'/'.dirname($template)."/".basename($template,substr($template,$pos)).'.php';
    }
    $isfileto = is_file($to);
    if($tplRefresh || !$isfileto) {
        $useTpl=($templatePath?YIFANG_ROOT.$templatePath:YIFANG_TEMPLATE.'/').$tplData["tpl"];
        $from = ($templatePath?YIFANG_ROOT.$templatePath:YIFANG_TEMPLATE.'/').$tplData["tpl"].'/'.$template.$extend;
        if(!is_file($from)) {
            $from = ($templatePath?YIFANG_ROOT.$templatePath:YIFANG_TEMPLATE.'/').$tplData["defaultTemplate"].'/'.$template.$extend;
            $useTpl=($templatePath?YIFANG_ROOT.$templatePath:YIFANG_TEMPLATE.'/').$tplData["defaultTemplate"];
        }
        if(!is_file($from)) {
            $from = YIFANG_CORE_TEMPLATE."/".$template.$extend;
        }
        if(!$isfileto || $tplRefresh==2){
            //实时刷新
            template_compile($from, $to,$useTpl);
        }else{
            //允许模版刷新
            if(filemtime($from) > filemtime($to) || (filesize($to) == 0 && filesize($from) > 0)){
                template_compile($from, $to,$useTpl);
            }
        }
    }
    return $to;
}

/**
 * 获取模板文件
 * @param string $template
 * @param null $templatePath
 */
function getTemplateFile($template = 'index',$templatePath){
    $tplData=getTplData();
    if(($pos=stripos($template,"."))===false){
        $extend='.html';
    }else{
        $extend="";
    }
    $defaultTpl=YIFANG_TEMPLATE."/{$tplData['defaultTemplate']}";
    $selTpl=YIFANG_TEMPLATE."/{$tplData['tpl']}";
    if($defaultTpl==$templatePath){
        $from = $defaultTpl.'/'.$template.$extend;
    }else{
        if($templatePath){
            $from = $templatePath."/".$template.$extend;
            if(!is_file($from)) {
                $from = $selTpl.'/'.$template.$extend;
            }
            if(!is_file($from)) {
                $from = $defaultTpl.'/'.$template.$extend;
            }
        }else{
            $from = $defaultTpl.'/'.$template.$extend;
        }
    }
    return $from;
}

/**
 * 获取模版内容
 * @param $template
 * @return string
 */
function ob_template($template, $data=null,$templatePath=null) {
    if($data){
        extract($data, EXTR_OVERWRITE);
        unset($data);
    }
    ob_start();
    $file= template($template,$templatePath);
    include $file;
    $contents = ob_get_contents();
    ob_clean();
    return $contents;
}

/**
 * 执行模版内容
 * @param $template
 * @return string
 */
function ob_exec_template($template, $data=null,$templatePath=null) {
    $file= template($template,$templatePath);
    if(is_file($file)){
        if($data){
            extract($data, EXTR_OVERWRITE);
            unset($data);
        }
        ob_start();
        include $file;
        ob_clean();
        return true;
    }else{
        return false;
    }
}

/**
 * 模板编译
 * @param $from
 * @param $to
 */
function template_compile($from, $to,$useTpl) {
    $str=getFileContent($from);
    $str=includeReplace($str,$useTpl);
    //替换include模板
    $str = template_parse($str);
    $content = varReplace($str);
    if(function_exists("getCopyrightInfo")){
        getCopyrightInfo($content);
    }
    fileWrite($to, $content);
}

function replateAbc($str){
    return trim($str," '\"");
}

/**
 * 加载模板
 */
function includeReplace($str,$useTpl){
    $regMap=array(
        "/\{include\s+([^\}]+)\s?\}/",
    );
    foreach($regMap as $reg){
        $ok=preg_match_all($reg,$str,$matachs);
        if($ok >0){
            $match_str=$matachs[0];
            $match_params=$matachs[1];
            foreach($match_str as $key=>$val){
                $tempParams=isset($match_params[$key])?$match_params[$key]:"";
                $params=array_map("replateAbc",explode(" ",$tempParams));
                $tempName=isset($params[0])?$params[0]:"";
                $templatePath=isset($params[1])?$params[1]:"";

                $search=$val;
                $replace="";
                $tempDir=$templatePath?YIFANG_ROOT.$templatePath:"";
                $tpl=$tempDir?$tempDir:$useTpl;
                $tempFile=getTemplateFile($tempName,$tpl);

                if(is_file($tempFile)){
                    $replace=file_get_contents($tempFile);
                    $replace=includeReplace($replace,$useTpl);
                }
                $str=str_replace($search,$replace,$str);
            }
        }
    }
    return $str;
}

function preg_prefix_loop_callback($matchs){
    $suffix=uniqueStr();
    $tmp='<?php 
    $tagParams=<<<EOD
'.$matchs[2].'
EOD;
$extra=array();
if("'.$matchs[1].'"=="page"){
   if(isset($tagPage)){
        $extra["data"]=$tagPage;
   }
}
$tagResult_'.$suffix.' = YiFangTag("'.$matchs[1].'",$tagParams,$extra); 
$tagKey_'.$suffix.'=$tagResult_'.$suffix.'["sysParam"]["key"];
$tagVal_'.$suffix.'=$tagResult_'.$suffix.'["sysParam"]["val"];
$tagData_'.$suffix.'=array();
if($tagResult_'.$suffix.'["sysParam"]["render"]=="paging"){
    if(isset($tagResult_'.$suffix.'["data"]["data"])){
        $tagPage=$tagResult_'.$suffix.'["data"];
        unset($tagPage["data"]);
        $tagPage=toJsonEncode($tagPage);
        $tagData_'.$suffix.'=$tagResult_'.$suffix.'["data"]["data"];
    }
}else{
    if(isset($tagResult_'.$suffix.'["data"])){
        if($tagResult_'.$suffix.'["sysParam"]["row"]=="1"){
            $tagData_'.$suffix.'=array($tagResult_'.$suffix.'["data"]);
        }else{
            $tagData_'.$suffix.'=$tagResult_'.$suffix.'["data"];
        }
    }
}
if($tagResult_'.$suffix.'["sysParam"]["receiveName"]){
    $receiveName_'.$suffix.'=$tagResult_'.$suffix.'["sysParam"]["receiveName"];
    $$receiveName_'.$suffix.'=$tagData_'.$suffix.';
}else{
    if(!$tagData_'.$suffix.'){
        echo $tagResult_'.$suffix.'["sysParam"]["noneStr"];
    }else{
        if(!is_array($tagData_'.$suffix.')){
            echo $tagData_'.$suffix.';
        }else{
            foreach($tagData_'.$suffix.' as $$tagKey_'.$suffix.' => $$tagVal_'.$suffix.'){ 
                ?>
';
    return $tmp;
}

function preg_suffix_loop_callback($matchs){
    $tmp='<?php
            }
        }
    }
}
?>';
    return $tmp;
}

function preg_no_loop_callback($matchs){
    $suffix=uniqueStr();
    $tmp='<?php 
    $tagParams=<<<EOD
'.$matchs[2].'
EOD;
$extra=array();
if("'.$matchs[1].'"=="page"){
   if(isset($tagPage)){
        $extra["data"]=$tagPage;
   }
}
$tagResult_'.$suffix.' = YiFangTag("'.$matchs[1].'",$tagParams,$extra); 
$tagKey_'.$suffix.'=$tagResult_'.$suffix.'["sysParam"]["key"];
$tagVal_'.$suffix.'=$tagResult_'.$suffix.'["sysParam"]["val"];
$tagData_'.$suffix.'=array();
if(isset($tagResult_'.$suffix.'["data"])){
    $tagData_'.$suffix.'=$tagResult_'.$suffix.'["data"];
}
if($tagResult_'.$suffix.'["sysParam"]["receiveName"]){
    $receiveName_'.$suffix.'=$tagResult_'.$suffix.'["sysParam"]["receiveName"];
    $$receiveName_'.$suffix.'=$tagData_'.$suffix.';
}else{
    if(!$tagData_'.$suffix.'){
        echo $tagResult_'.$suffix.'["sysParam"]["noneStr"];
    }else{
        if(!is_array($tagData_'.$suffix.')){
            echo $tagData_'.$suffix.';
        }
    }
}
?>
';
    return $tmp;
}

/**
 * 嵌套模板解析
 * @param $str
 */
function template_nesting_parse($str){
    $tagList=array(
        "yifang",
        "YiFang",
        "LTcms",
    );
    foreach($tagList as $tag){
        $searchStartLoop=array(
            "/\{{$tag}:(\S+)\s([^\}\/]*)\}/is",
        );
        $str=preg_replace_callback($searchStartLoop,"preg_prefix_loop_callback",$str);
        $searchEndLoop=array(
            "/\{\/{$tag}:(\S+)\}/is",
        );
        $str=preg_replace_callback($searchEndLoop,"preg_suffix_loop_callback",$str);
        $searchNoLoop=array(
            "/\{{$tag}:(\S+)\s([^\}\/]*)\/\}/is",
        );
        $str=preg_replace_callback($searchNoLoop,"preg_no_loop_callback",$str);
    }
    return $str;
}

/**
 * 模板标签解析
 * @param $str
 * @return mixed
 */
function template_parse($str) {
    /**
     * 去除注释
     */
    $str = preg_replace("/\<\!\-\-\[(.+?)\]\-\-\>/", "", $str);

    /**
     * 执行php源代码
     */
    $str = preg_replace("/\<\!\-\-\{php([\s\S]+)\}\-\-\>/", "<?php \\1 ?>", $str);
    $str = preg_replace("/\{php\s+(.+?)\}/", "<?php \\1?>", $str);

    /**
     * 执行括号内容
     */
    $str = preg_replace("/\<\!\-\-\{(.+?)\}\-\-\>/s", "{\\1}", $str);

    /**
     * if 控制流程
     */
    $str = preg_replace("/\{if\s+(.+?)\}/", "<?php if(\\1) { ?>", $str);
    $str = preg_replace("/\{else\}/", "<?php } else { ?>", $str);
    $str = preg_replace("/\{elseif\s+(.+?)\}/", "<?php } else if(\\1) { ?>", $str);
    $str = preg_replace("/\{\/if\}/", "<?php } ?>", $str);

    /**
     * 数组循环
     */
    $str = preg_replace("/\{foreach\s+(\S+)\s+(\S+)\}/", "<?php if(is_array(\\1)) { foreach(\\1 as \\2) { ?>", $str);
    $str = preg_replace("/\{foreach\s+(\S+)\s+(\S+)\s+(\S+)\}/", "<?php if(is_array(\\1)) { foreach(\\1 as \\2 => \\3) { ?>", $str);
    $str = preg_replace("/\{\/foreach\}/", "<?php } } ?>", $str);

    /**
     * 匹配函数
     */
    $str = preg_replace("/\{([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*\(([^{}]*)\))\}/", "<?php echo \\1;?>", $str);

    /**
     * 添加单引号
     */
    $str = preg_replace_callback("/<\?php([^\?]+)\?>/s", "template_addquote1", $str);

    /**
     * 匹配变量
     */
    $str = preg_replace("/\{(\\$[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\+\-\x7f-\xff]*)([^}].*?)\}/", "<?php echo \\1\\2; ?>", $str);

    /**
     * 匹配常量
     */
    $str = preg_replace("/\{([A-Z_\x7f-\xff][A-Z0-9_\x7f-\xff]*)\}/s", "<?php echo \\1;?>", $str);

    /**
     * 合并换行
     */
    $str = preg_replace("/(\r?\n)\\1+/", "\\1", $str);

    $str = preg_replace("/\{break\}/", "<?php break; ?>", $str);
    $str = preg_replace("/\{continue\}/", "<?php continue; ?>", $str);

    /**
     * 去除制表符
     */
    $str = str_replace("\t", '', $str);

    /**
     * 自定义标签
     */
    $str=template_nesting_parse($str);

    $replaces=config("template.replace","");
    if($replaces){
        $find=array();
        $replace=array();
        foreach($replaces as $rkey=>$rval){
            $find[]=$rkey;
            $replace[]=$rval;
        }
        $str=str_replace($find,$replace,$str);
    }
    $str = "<?php defined('IN_YiFang') or exit('Access Denied');?>".trim($str);
    return $str;
}

/**
 * 添加引用1
 * @param $matches
 * @return mixed
 */
function template_addquote1($matches) {
    return str_replace("\\\"", "\"", preg_replace("/\[([a-zA-Z0-9_\-\.\x7f-\xff]+)\]/s", "['\\1']", $matches[0]));
}
